﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CLVisionTcpIP
{
    public class CLTcpClient
    {
        private System.Net.Sockets.TcpClient _client;
        private NetworkStream _stream;
        private Thread _receiveThread;
        private Timer _heartbeatTimer;
        private bool _connected;
        public Action<string> OnMessageReceived;
        public void Connect(string serverIp, int port)
        {
            _client = new System.Net.Sockets.TcpClient();
            _client.Connect(serverIp, port);
            _stream = _client.GetStream();
            _connected = true;
            OnMessageReceived("已连接服务器。");

            _receiveThread = new Thread(ReceiveLoop) { IsBackground = true };
            _receiveThread.Start();

            _heartbeatTimer = new Timer(SendHeartbeat, null, 0, 5000);
        }

        public void Send(string message)
        {
            if (!_connected) return;
            byte[] data = Encoding.UTF8.GetBytes(message);
            _stream.Write(data, 0, data.Length);
        }

        private void ReceiveLoop()
        {
            byte[] buffer = new byte[1024];
            try
            {
                while (_connected)
                {
                    int bytesRead = _stream.Read(buffer, 0, buffer.Length);
                    if (bytesRead == 0) break;
                    string msg = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                    if (msg == "HEARTBEAT_ACK") continue;
                    OnMessageReceived("收到服务器消息: " + msg);
                }
            }
            catch { }
            finally
            {
                _connected = false;
                OnMessageReceived("与服务器断开连接。");
            }
        }

        private void SendHeartbeat(object state)
        {
            if (!_connected) return;
            try
            {
                byte[] data = Encoding.UTF8.GetBytes("HEARTBEAT");
                _stream.Write(data, 0, data.Length);
            }
            catch
            {
                _connected = false;
                OnMessageReceived("心跳失败，已断开。");
            }
        }

        public void Disconnect()
        {
            _connected = false;
            _heartbeatTimer?.Dispose();
            _client?.Close();
        }
    }
}
